package com.ruoyi.common.utils.oss;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.ruoyi.common.exception.ServiceException;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * OSS工具类
 * 
 * @author ruoyi
 */
public class OssUtils
{
    // OSS配置信息
    private static final String ENDPOINT = "https://oss-cn-beijing.aliyuncs.com";
    private static final String ACCESS_KEY_ID = "LTAI5tHyosRYM3iKrxe6fFLQ";
    private static final String ACCESS_KEY_SECRET = "6E31BmiammvnWnMh5ghoD6sQMKE7Lw";
    private static final String BUCKET_NAME = "ruoyi-video1";
    private static final String DOMAIN = "https://ruoyi-video1.oss-cn-beijing.aliyuncs.com";

    /**
     * 上传文件到OSS
     * 
     * @param file 上传的文件
     * @param folder 文件夹名称
     * @return 文件访问URL
     */
    public static String uploadFile(MultipartFile file, String folder)
    {
        if (file == null || file.isEmpty())
        {
            throw new ServiceException("上传文件不能为空");
        }

        // 创建OSSClient实例
        OSS ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);

        try
        {
            // 获取文件原始名称
            String originalFilename = file.getOriginalFilename();
            if (originalFilename == null || originalFilename.isEmpty())
            {
                throw new ServiceException("文件名不能为空");
            }

            // 获取文件扩展名
            String extension = "";
            int lastDotIndex = originalFilename.lastIndexOf(".");
            if (lastDotIndex > 0)
            {
                extension = originalFilename.substring(lastDotIndex);
            }

            // 生成唯一文件名
            String fileName = folder + "/" + UUID.randomUUID().toString() + extension;

            // 获取文件输入流
            InputStream inputStream = file.getInputStream();

            // 创建PutObjectRequest对象
            PutObjectRequest putObjectRequest = new PutObjectRequest(BUCKET_NAME, fileName, inputStream);

            // 上传文件
            ossClient.putObject(putObjectRequest);

            // 返回文件访问URL
            return DOMAIN + "/" + fileName;
        }
        catch (IOException e)
        {
            throw new ServiceException("文件上传失败：" + e.getMessage());
        }
        finally
        {
            // 关闭OSSClient
            ossClient.shutdown();
        }
    }

    /**
     * 上传图片文件
     * 
     * @param file 图片文件
     * @return 图片访问URL
     */
    public static String uploadImage(MultipartFile file)
    {
        // 检查文件类型
        String contentType = file.getContentType();
        if (contentType == null || !contentType.startsWith("image/"))
        {
            throw new ServiceException("只能上传图片文件");
        }

        return uploadFile(file, "images");
    }

    /**
     * 上传视频文件
     * 
     * @param file 视频文件
     * @return 视频访问URL
     */
    public static String uploadVideo(MultipartFile file)
    {
        // 检查文件类型
        String contentType = file.getContentType();
        if (contentType == null || !contentType.startsWith("video/"))
        {
            throw new ServiceException("只能上传视频文件");
        }

        return uploadFile(file, "videos");
    }

    /**
     * 删除OSS文件
     * 
     * @param fileUrl 文件URL
     * @return 是否删除成功
     */
    public static boolean deleteFile(String fileUrl)
    {
        if (fileUrl == null || fileUrl.isEmpty())
        {
            return false;
        }

        // 从URL中提取文件路径
        String filePath = fileUrl.replace(DOMAIN + "/", "");

        // 创建OSSClient实例
        OSS ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);

        try
        {
            // 删除文件
            ossClient.deleteObject(BUCKET_NAME, filePath);
            return true;
        }
        catch (Exception e)
        {
            return false;
        }
        finally
        {
            // 关闭OSSClient
            ossClient.shutdown();
        }
    }
}
